using System;
using System.IO;
using System.Web;
using PHSRAG.Insight21.Common.Pages;
using PHSRAG.Insight21.Policy;
using PHSRAG.Utility;

namespace PHSRAG.Insight21.Humans
{
    /// <summary>
    /// This page is used to display a PDF representaion of the specified
    /// protocol or protocol process.  The protocol XML is first converted to a
    /// PDF by applying XSLFO to the Ibex PDF generator.  Based on the
    /// incoming querystring value, attachements will also be converted and added to the
    /// generated PDF.
    /// </summary>
    public partial class ViewProtocolPage : BasePage
    {
        #region Instance variables

        private ICachePolicy _cachePolicy;
        private ICachePolicy _pageCachePolicy;
        private Protocol _protocol;
        private string _protocolId;

        #endregion

        #region Private Properties

        private Protocol Protocol
        {
            get
            {
                string cacheKey = Protocol.ProtocolKey;
                _protocol = _cachePolicy.GetCachedObject(cacheKey) as Protocol;

                if ((_protocol == null))
                {
                    _protocol = new Protocol(_cachePolicy);
                    _protocol.Load(DataAccess.GetConnectionString(), Convert.ToInt32(_protocolId));
                    _cachePolicy.Cache(cacheKey, _protocol);
                }
                return _protocol;
            }
        }

        #endregion

        #region Page Event Handlers

        /// <summary>
        /// Creates a pdf version of the IRB Application and displays it to the user
        /// </summary>
        /// <param name="sender">Object that raised the event.</param>
        /// <param name="e">Arguments associated with the event.</param>
        protected void Page_Load(object sender, EventArgs e)
        {
            try
            {
                string viewApplicationType = Constants.ViewApplicationType.Simple;
                object viewAppType = Request.QueryString["ViewApplicationType"];
                string docStageFolderEntry = Settings.GetKeyValue("DocumentStagingFolder", "DocumentStagingFolder");
                ProtocolProcess protocolProcess = null;


                /*This is a quick fix to prevent postback when "current view" is 
                 * clicked from ProtocolDetails Page.
                 * We need to approach this implementation later to refine it further.
                 */
                string currentViewRequest = Request.QueryString["currentview"];
                string reportName = Request.QueryString["Report"];

                if (!string.IsNullOrEmpty(currentViewRequest))
                {
                    _protocolId = Request.QueryString["ProtocolId"];

                    ProtocolVersion protocolVersion =
                        Protocol.GetLatestApplicationVersion(Convert.ToInt32(_protocolId), DataAccess.ConnectionString, false, _cachePolicy);

                    if (null == protocolVersion)
                    {
                        throw new ApplicationException(string.Format("An {0} initial review does not exist for this protocol.",
                            (Protocol.ModuleType == Constants.ModuleType.Humans) ? "eIRB" : "eIACUC"));
                    }
                    protocolProcess =
                        ProtocolProcess.GetProtocolProcess(DataAccess.ConnectionString, protocolVersion.ProtocolProcessId, _cachePolicy, null);


                    protocolProcess.Cache();
                    protocolVersion.Cache();
                }
                    //if Request is coming from ViewProtocoldetails page,IR grids
                else if (reportName != null && reportName.ToLower() == "view")
                {
                    string protocolProcessId = Request.QueryString["ProtocolProcessId"];
                    if (!string.IsNullOrEmpty(protocolProcessId))
                    {
                        protocolProcess =
                            ProtocolProcess.GetProtocolProcess(DataAccess.ConnectionString, Convert.ToInt32(protocolProcessId), _cachePolicy, null);
                        protocolProcess.Cache();

                        if (Constants.ProtocolProcessType.InitialReview == protocolProcess.Type ||
                            Constants.AnimalProtocolProcessType.InitialReview == protocolProcess.Type)
                        {
                            ProtocolVersion protocolVersion = ((Application) protocolProcess).GetInitiallyApprovedVersion();
                            if (null != protocolVersion)
                            {
                                protocolVersion.Cache();
                            }
                            viewApplicationType = Constants.ViewApplicationType.FullUsingProtocolInformation;
                        }
                        else
                        {
                            ProtocolVersion protocolVersion = _cachePolicy.GetCachedObject(ProtocolVersion.ProtocolVersionKey) as ProtocolVersion;
                            if (null != protocolVersion)
                            {
                                protocolVersion.UnCache();
                            }
                            //viewApplicationType = Constants.ViewApplicationType.Full;
                            viewApplicationType = "View";
                        }
                    }
                }
                else
                {
                    protocolProcess = _cachePolicy.GetCachedObject(ProtocolProcess.ProtocolProcessKey) as ProtocolProcess;
                }

                if (null != viewAppType)
                {
                    viewApplicationType = Convert.ToString(viewAppType);
                }


                if (null == protocolProcess)
                {
                    throw new Exception("View Application (PDF): The protocol process cannot be null");
                }

                //example: docStagingFolder = \\PHSWEB418\DocumentStagingFolder
                string docStagingFolder = string.Format(@"\\{0}",
                    Path.Combine(HttpContext.Current.Server.MachineName, docStageFolderEntry));

                InsightServiceUtility.DocumentUtility documentUtility = new InsightServiceUtility.DocumentUtility();
                documentUtility.Timeout = -1;
                string outputFile;
                /* VFA Implemetation TrackIT 9298*/
                if (protocolProcess.Locked)
                {
                    outputFile = documentUtility.GetAppDocumentForLockedProcess(protocolProcess.Id, docStagingFolder, viewApplicationType,
                     protocolProcess.Locked, protocolProcess.ProtocolId);
                }
                else
                {
                    outputFile = documentUtility.GetApplicationDocument(protocolProcess.Id, docStagingFolder, viewApplicationType);
                }


                if (outputFile == null)
                {
                    throw new Exception("View Application (PDF): GetApplicationDocument returned a NULL value. Output file is empty");
                }
                Response.Clear();
                Response.ClearHeaders();
                Response.AppendHeader("content-disposition", "attachment; filename=Application.pdf");
                Response.ContentType = "Application/pdf";
                try
                {
                    Response.TransmitFile(outputFile);
                    Response.End();
                }
                catch (Exception ex)
                {
                    ExceptionReport.WriteToEventLog(String.Format("Failed while transmitting the file {0} to the client.", outputFile),
                        ex, true, ExceptionReport.ReportType.Error);
                }
            }
            catch (Exception ex)
            {
                annunciator.Title = InsightUtilities.Constants.Annunciator.Title;
                annunciator.Message = ExceptionReport.GetExceptionInfo(ex, false);
            }
        }

        #endregion

        #region Web Form Designer generated code

        /// <summary>
        /// Form Initialization
        /// </summary>
        /// <param name="e">Arguments associated with the event.</param>
        protected override void OnInit(EventArgs e)
        {
            InitializeComponent();
            base.OnInit(e);
            _cachePolicy = (Policy.ICachePolicy) Session[Policy.Names.CachePolicyKey];
            _pageCachePolicy = (Policy.ICachePolicy) Session[Policy.Names.PageCachePolicyKey];
        }

        /// <summary>
        /// Required method for Designer support - do not modify
        /// the contents of this method with the code editor.
        /// </summary>
        private void InitializeComponent()
        {
            this.ID = "ViewProtocolPAge";
        }

        #endregion
    }
}